package utils

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"
)

// IPInfo IP信息结构体
type IPInfo struct {
	IP       string `json:"ip"`
	Country  string `json:"country"`
	Region   string `json:"region"`
	City     string `json:"city"`
	ISP      string `json:"isp"`
	Location string `json:"location"`
}

// GetIPLocation 获取IP地理位置信息
func GetIPLocation(ip string) (string, error) {
	// 检查是否为本地IP
	if isLocalIP(ip) {
		return "本地网络", nil
	}

	// 创建HTTP客户端
	client := &http.Client{
		Timeout: 5 * time.Second,
	}

	// 使用淘宝IP查询接口
	url := fmt.Sprintf("http://ip.taobao.com/outGetIpInfo?ip=%s&accessKey=alibaba-inc", ip)
	resp, err := client.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	// 解析JSON响应
	var result struct {
		Code int `json:"code"`
		Data struct {
			Country string `json:"country"`
			Region  string `json:"region"`
			City    string `json:"city"`
			ISP     string `json:"isp"`
		} `json:"data"`
	}

	if err := json.Unmarshal(body, &result); err != nil {
		return "", err
	}

	// 检查是否成功
	if result.Code != 0 {
		return "未知位置", nil
	}

	// 构建位置字符串
	location := strings.TrimSpace(result.Data.Country)
	if location != "" && result.Data.Region != "" && result.Data.Region != "XX" {
		location += " " + strings.TrimSpace(result.Data.Region)
	}
	if location != "" && result.Data.City != "" && result.Data.City != "XX" {
		location += " " + strings.TrimSpace(result.Data.City)
	}
	if location == "" {
		location = "未知位置"
	}

	return location, nil
}

// isLocalIP 检查是否为本地IP
func isLocalIP(ip string) bool {
	if ip == "127.0.0.1" || ip == "localhost" || ip == "::1" {
		return true
	}
	if strings.HasPrefix(ip, "192.168.") || strings.HasPrefix(ip, "10.") ||
		strings.HasPrefix(ip, "172.16.") || strings.HasPrefix(ip, "172.17.") ||
		strings.HasPrefix(ip, "172.18.") || strings.HasPrefix(ip, "172.19.") ||
		strings.HasPrefix(ip, "172.20.") || strings.HasPrefix(ip, "172.21.") ||
		strings.HasPrefix(ip, "172.22.") || strings.HasPrefix(ip, "172.23.") ||
		strings.HasPrefix(ip, "172.24.") || strings.HasPrefix(ip, "172.25.") ||
		strings.HasPrefix(ip, "172.26.") || strings.HasPrefix(ip, "172.27.") ||
		strings.HasPrefix(ip, "172.28.") || strings.HasPrefix(ip, "172.29.") ||
		strings.HasPrefix(ip, "172.30.") || strings.HasPrefix(ip, "172.31.") {
		return true
	}
	return false
}
